package pers.qianyu.month_202012.date_20201210;

import java.util.*;

/**
 * 52. N皇后 II
 * https://leetcode-cn.com/problems/n-queens-ii/
 *
 * @author mizzle rain
 * @date 2020-12-10 15:26
 */
public class SolveNQueensTwo {
    int res;

    public int totalNQueens(int n) {
        char[][] track = new char[n][n];
        for (int i = 0; i < track.length; i++) {
            Arrays.fill(track[i], '.');
        }
        recur(track, n - 1);
        return res;
    }

    private void recur(char[][] track, int row) {
        if (row < 0) {
            res++;
            return;
        }
        for (int k = 0; k < track.length; k++) {
            if (isInvalid(track, row, k)) {
                continue;
            }
            track[row][k] = 'Q';
            recur(track, row - 1);
            track[row][k] = '.';
        }
    }

    private boolean isInvalid(char[][] track, int i, int j) {
        int len = track.length;
        for (int k = 0; k < len; k++) {
            if (track[i][k] == 'Q') {
                return true;
            }
            if (track[k][j] == 'Q') {
                return true;
            }
        }
        int p1 = i + 1, p2 = j + 1;
        while (p1 < len && p2 < len) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1++;
            p2++;
        }
        p1 = i - 1;
        p2 = j - 1;
        while (p1 >= 0 && p2 >= 0) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1--;
            p2--;
        }
        p1 = i + 1;
        p2 = j - 1;
        while (p1 < len && p2 >= 0) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1++;
            p2--;
        }
        p1 = i - 1;
        p2 = j + 1;
        while (p1 >= 0 && p2 < len) {
            if (track[p1][p2] == 'Q') {
                return true;
            }
            p1--;
            p2++;
        }
        return false;
    }
}